package com.example.springbootdemo.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 跨域过滤器
public class CrossFilter implements Filter {

    private List<String> allowOrigin;

    public void setAllowOrigin(List<String> allowOrigin) {
        this.allowOrigin = allowOrigin;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse) res;
//         response.setHeader("Access-Control-Allow-Origin", "http://localhost:63343/");
        /** Access-Control-Allow-Origin只允许设置一个值
         for(String origin: allowOrigin) {
             response.setHeader("Access-Control-Allow-Origin", origin);
         }
         */
        String currentOrigin = request.getHeader("Origin");
        // 不是跨域访问, 因为跨域访问浏览器会自动的携带 Origin参数.
        if(null == currentOrigin) {
            chain.doFilter(req, res);
            return;
        }

        if(allowOrigin.contains(currentOrigin)) {
            response.setHeader("Access-Control-Allow-Origin", currentOrigin);
        }else {
            return;
        }
        response.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    }
}
